const config = require('../constants/config.js');

const toJSON = (data) => {
  return JSON.stringify(data)
}

const getRandomNumber = (excludeArray) => {
  const num = 22;

  while (true) {
    const randomNumber = Math.floor(Math.random() * (num + 1));
    if (!excludeArray) {
      return randomNumber;
    }
    if (!excludeArray.includes(randomNumber)) {
      return randomNumber;
    }
  }
}

const getDate = () => {
  const currentDate = new Date();

  const year = currentDate.getFullYear();
  const month = String(currentDate.getMonth() + 1).padStart(2, '0');
  const day = String(currentDate.getDate()).padStart(2, '0');

  return `${year}${month}${day}`;
}

const getShowConfig = () => {
  let randomNum = null

  try {
    var value = wx.getStorageSync('cardData')
    if (value) {
      const storageData = JSON.parse(value)
      
      if (getDate() === storageData.date) {
        randomNum = storageData.intraday
      } else {
        const historyData = storageData.data
        console.log(4, historyData.length)
        if (historyData.length === 23) {
          randomNum = getRandomNumber([storageData.intraday]);
          wx.setStorage({
            key: 'cardData',
            data: toJSON({
              date: getDate(),
              intraday: randomNum,
              data: [randomNum]
            })
          })
        } else {
          randomNum = getRandomNumber(historyData);
          
          wx.setStorage({
            key: 'cardData',
            data: toJSON({
              date: getDate(),
              intraday: randomNum,
              data: [...historyData, randomNum]
            })
          })
        }
      }
    } else {
      randomNum = getRandomNumber();
      wx.setStorage({
        key: 'cardData',
        data: toJSON({
          date: getDate(),
          intraday: randomNum,
          data: [randomNum]
        })
      })
    }
  } catch (e) {
    console.log('失败', e)
    // Do something when catch error
  }

  console.log('当前', randomNum, config[randomNum])
  return config[randomNum]
}

module.exports = getShowConfig